import { createRouter, createWebHashHistory } from "vue-router";
import { useRoleStore } from "@/store/modules/roles";
import { setAuth } from "@/utils/auth";
import { message } from "ant-design-vue";
import API from "@/api/system";
const routes = [
  {
    path: "/",
    meta: {
      title: "",
      KeepAlive: false,
    },
    name: "layout",
    redirect: "/home",
    component: () => import("../components/layouts/index.vue"),
    children: [

    ],
  },
  {
    path: "/homeLayout",
    meta: {
      title: "伏羲東方数字化智慧云平台",
      KeepAlive: false,
    },
    component: () => import("../views/homeLayout/index.vue"),
    children: [
      {
        path: "/index",
        meta: {
          title: "伏羲東方数字化智慧云平台",
          KeepAlive: false,
        },
        component: () => import("../views/home/index/index.vue"),
      },
      {
        path: "/emulation",
        meta: {
          title: "虚拟仿真实验",
          KeepAlive: false,
        },
        component: () => import("../views/home/emulation/emulation.vue"),
      },
      {
        path: "/laboratory",
        meta: {
          title: "数字化实验室",
          KeepAlive: false,
        },
        component: () => import("../views/home/laboratory/laboratory.vue"),
      },
      {
        path: "/ai",
        meta: {
          title: "AI实验助手",
          KeepAlive: false,
        },
        component: () => import("../views/home/ai/ai.vue"),
      },
      {
        path: "/wiki",
        meta: {
          title: "实验仪器百科",
          KeepAlive: false,
        },
        component: () => import("../views/home/wiki/wiki.vue"),
      },
    ],
  },
  {
    path: "/wiki-detail",
    meta: {
      title: "实验仪器百科详情",
      KeepAlive: false,
    },
    component: () => import("../views/home/wiki/detail.vue"),
  },

  {
    path: "/login",
    meta: {
      title: "登录",
      KeepAlive: false,
    },
    component: () => import("../views/system/login/index.vue"),
  },
  {
    path: "/register",
    meta: {
      title: "登录",
      KeepAlive: false,
    },
    component: () => import("../views/system/regist/index.vue"),
  },
  {
    path: "/personal",
    meta: {
      title: "个人中心",
      KeepAlive: false,
    },
    component: () => import("../views/system/personal/index.vue"),
  },
  {
    path: "/share1",
    meta: {
      title: "AI云实验",
      KeepAlive: false,
    },
    component: () => import("../views/share/share1.vue"),
  },
  {
    path: "/share3",
    meta: {
      title: "AI云实验",
      KeepAlive: false,
    },
    component: () => import("../views/share/share3.vue"),
  },
  // {
  //   path: "/question",
  //   meta: {
  //     title: "常见问题",
  //     KeepAlive: false,
  //   },
  //   component: () => import("../views/system/question/index.vue"),
  // },

];
const router = createRouter({
  history: createWebHashHistory(),
  routes,
});

/** 路由前置守卫 **/
let isFirst = true;
//增加白名单
const whiteList = [
  "/index",
  "/register",
  "/ai",
  "/wiki",
  "/wiki-detail",
  "/emulation",
  "/laboratory",
  "/home",
  '/share1',
  '/share3'
];
router.beforeEach(async (to: any, from, next) => {
  const token = localStorage.getItem("token");
  // if (isFirst) {
  //   addRoutes()
  //   isFirst = false
  //   next(to.fullPath)
  // } else {
  //   next()
  // }
  //增加白名单
  if (whiteList.includes(to.path)) {
    if (to.path == '/home') {
      if (to.query.token) {
        message.success("登录成功");
        localStorage.setItem("token", to?.query?.token);
        let info: any = await API.MyProfile({});
        localStorage.setItem("role", info.user_type_id);
        localStorage.setItem("userInfo", JSON.stringify(info));
        if (isFirst) {
          addRoutes();
          isFirst = false;
          next('/home');
        } else {
          next();
        }
      } else if (to.query.error) {
        message.error(to.query.error);
        next("/login");
      } else {
        if (token) {
          if (isFirst) {
            addRoutes();
            isFirst = false;
            next(to.fullPath);
          } else {
            next();
          }
        } else {
          next("/index");
        }
      }
    } else {
      next();
    }
  } else {
    if (token) {
      if (to.path === "/login") {
        next("/");
      } else {
        if (isFirst) {
          addRoutes();
          isFirst = false;
          next(to.fullPath);
        } else {
          next();
        }
      }
    } else {
      if (to.path === "/login") {
        next();
      } else {
        next("/login");
      }
    }
  }
});
//动态加载路由
function addRoutes() {
  const role: any = localStorage.getItem("role");
  setAuth(role);
  const roleStore = useRoleStore();
  const menuList = roleStore.menuList;
  // 优化 glob 导入模式
  const pages = import.meta.glob("../views/**/*.vue", { eager: false });
  function normalizePath(path: string) {
    return path.replace(/^\/?/, '../views/').replace(/\.vue$/i, '') + '.vue';
  }
  // 获取现有路由
  const routes = router.getRoutes();
  if (!routes.length) {
    console.error("未找到基础路由");
    return;
  }

  // 获取布局路由（假设第一个是根布局路由）
  const layoutRoute = routes[0];

  // 检查是否已经添加过路由
  if (menuList.length === 0) return;

  // 创建新的路由映射
  const newRoutes: any = [];

  menuList.forEach((item: any) => {
    // 处理父路由
    const route: any = {
      path: "/" + item.path,
      component: item.component
        ? pages[normalizePath(item.component)]
        : undefined,
      meta: {
        title: item.title,
        label: item.label,
        KeepAlive: false,
        isLayout: item.isLayout,
      },
      children: [],
    };

    // 处理子路由
    if (item.children?.length > 0) {
      item.children.forEach((child: any) => {
        const childRoute: any = {
          path: child.path.startsWith("/") ? child.path : `/${child.path}`, // 标准化路径
          component:
            child.component
              ? pages[normalizePath(child.component)]
              : undefined,
          meta: {
            title: child.title,
            label: child.label,
            KeepAlive: false,
            isLayout: child.isLayout,
          },
        };

        route.children?.push(childRoute);
      });
    }

    newRoutes.push(route);
  });

  // 先移除可能存在的旧路由
  newRoutes.forEach((route: any) => {
    if (router.hasRoute(route.name || route.path)) {
      router.removeRoute(route.name || route.path);
    }
  });

  // 添加新路由到根布局下
  newRoutes.forEach((route: any) => {
    router.addRoute(layoutRoute.name || "Layout", route);
  });

  // 可选：打印调试信息
  //console.log('动态路由添加完成', router.getRoutes());
}

export default router;
